﻿using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http.Headers;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace SendMailServer
{
    class DifyConection: IConnection
    {
        public class DifyConfig
        {
            public string BaseUrl { get; set; } = "http://192.168.2.231:480";
            public string ApiPath { get; set; } = "v1/chat-messages";
            public string ResponseMode { get; set; } = "streaming";
            public string DefaultUser { get; set; } = "abc-123";
            public string ApiKey { get; set; }= "app-jVlKhNrazyL4zEJyoNhDC0CV";
            public string ConversationId { get; set; }
        }

        private readonly DifyConfig _config = new DifyConfig();

        public DifyConfig Config { get { return _config; } }
        public EventHandler OnMessageGet;
        private string m_lastPostUrl;
        private string m_chatUid;

        public string LastPostUrl => m_lastPostUrl;

        public async void ChatAsync(string msg, string userName, string key, EventHandler handler)
        {
            m_chatUid=Guid.NewGuid().ToString();
            m_lastPostUrl = _config.BaseUrl + ";" + _config.ApiKey;

            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(_config.BaseUrl);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _config.ApiKey);

                var requestData = new
                {
                    inputs = new { },
                    query = msg,
                    response_mode = _config.ResponseMode,
                    conversation_id = _config.ConversationId,
                    user = userName ?? _config.DefaultUser,
                };

                var json = JsonConvert.SerializeObject(requestData);
                var content = new StringContent(json, Encoding.UTF8, "application/json");

                HttpResponseMessage response = await client.PostAsync(_config.ApiPath, content);
                if (response.IsSuccessStatusCode)
                {
                    using (var stream = await response.Content.ReadAsStreamAsync())
                    using (var reader = new StreamReader(stream))
                    {
                        StringBuilder fullResponse = new StringBuilder();
                        string line;
                        while ((line = await reader.ReadLineAsync()) != null)
                        {
                            if (line.StartsWith("data: "))
                            {
                                var json2 = line.Substring(6);
                                var jsonObj = JObject.Parse(json2);
                                var eventType = jsonObj["event"]?.ToString();

                                if (eventType == "message")
                                {
                                    var answer = jsonObj["answer"]?.ToString();
                                    if (!string.IsNullOrEmpty(answer))
                                    {
                                        fullResponse.Append(answer);
                                    }
                                    // 提取并更新conversationId
                                    var conversationId = jsonObj["conversation_id"]?.ToString();
                                    if (!string.IsNullOrEmpty(conversationId))
                                    {
                                        _config.ConversationId = conversationId;
                                    }
                                    if (handler != null)
                                    {
                                        handler(new ResMsg()
                                        {
                                            MsgCode = key,
                                            IsOk = true,
                                            Content = "UID="+m_chatUid+","+fullResponse.ToString(),
                                            UseSelfResponse = true
                                        }, null);
                                    }
                                }
                                else if (eventType == "message_end")
                                {
                                    break;
                                }
                            }
                        }
                    }
                }
                else
                {
                    throw new HttpRequestException($"Error: {response.StatusCode}");
                }
            }
        }

        #region 初始信息
        public ResMsg Load(string key)
        {
            return null;
        }
        public ResMsg Reload(string key)
        {
            return null;
        } 
        #endregion

        public ResMsg CreateNewTopic(JToken oldAttr, string userName, string key)
        {
            return null;
        }

        public class FileInfo
        {
            public string type { get; set; }
            public string transfer_method { get; set; }
            public string url { get; set; }
        }
    }
}
